package com.imooc.searchcountdown;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 使用countdownlatch优化多次查询
 * @author ChangLiang
 * @date 2019/3/5
 */
public class QueryThread implements Runnable {

    protected CountDownLatch countDownLatch;

    protected Object target;

    protected String methodName;

    protected Class<?>[] parameterTypes;

    protected Object[] params;

    protected List<String> list;

    public QueryThread(CountDownLatch countDownLatch, Object target, String methodName, Class<?>[]
            parameterTypes, Object[] params, List<String> list) {
        this.countDownLatch = countDownLatch;
        this.target = target;
        this.methodName = methodName;
        this.parameterTypes = parameterTypes;
        this.params = params;
        this.list = list;
    }

    @Override
    public void run() {
        try {
            query();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (countDownLatch != null) {
                countDownLatch.countDown();
            }
        }
    }

    public void query() {
        try {
            Method method = this.target.getClass().getDeclaredMethod(methodName, parameterTypes);
            Object returnValue = method.invoke(target, params);
            String value = returnValue != null ? returnValue.toString() : null;
            list.add(value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
